/*
 * @Author: szx
 * @Date: 2021-10-15 16:42:01
 * @LastEditTime: 2021-10-15 17:18:54
 * @Description:
 * @FilePath: \leetcode\38\38.go
 */
package main

import (
	"fmt"
	"strconv"
	"strings"
)

// 我的解法
// func countAndSay(n int) string {
// 	if n == 1 { //我的方法精简法
// 		return "1"
// 	}
// 	var str strings.Builder
// 	var forward string = countAndSay(n - 1)
// 	index := 0
// 	for index < len(forward) {
// 		cur := index
// 		for cur < len(forward) && forward[index] == forward[cur] {
// 			cur++
// 		}
// 		str.WriteString(strconv.Itoa(cur - index))
// 		str.WriteByte(forward[index])
// 		index = cur
// 	}
// 	return str.String()
// }

// 官方解法1，和我的差不多，只不过是把递归变成迭代了
func countAndSay(n int) string {
	prev := "1"
	for i := 2; i <= n; i++ {
		cur := &strings.Builder{}
		for j, start := 0, 0; j < len(prev); start = j {
			for j < len(prev) && prev[j] == prev[start] {
				j++
			}
			cur.WriteString(strconv.Itoa(j - start))
			cur.WriteByte(prev[start])
		}
		prev = cur.String()
	}
	return prev
}

func main() {
	fmt.Println(countAndSay(3))
}
